<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Exceptions\ErrorCode;
use App\Requests\UserRequest;
use App\Resources\UserProfileResource;
use App\Services\AuthService;
use App\Services\UserService;

class UserController extends Controller
{
    protected $authService;
    protected $userService;

    public function __construct(AuthService $authService, UserService $userService)
    {
        $this->authService = $authService;
        $this->userService = $userService;
    }

    public function changeAvatar(UserRequest $request)
    {
        $user = auth()->user();
        $avatar = $request->get('avatar');
        $this->userService->changeAvatar($user, $avatar);
        return response_success();
    }

    public function getLoginUserProfile()
    {
        $user = auth()->user();
        return new UserProfileResource($user);
    }

    public function register(UserRequest $request)
    {
        $data = $request->validated();
        // 验证手机验证码。
        if (!$this->authService->checkAuthCode($data['phone'], $data['area_code'], $data['auth_code'])) {
            throw new ApiException('验证码无效！', ErrorCode::INVALID_AUTH_CODE);
        }
        // 注册用户。
        $user = $this->userService->register($data);
        // 返回 access_token。
        $access_token = auth()->tokenById($user->id);
        return response_with_token($access_token);
    }

    public function updateUserProfile(UserRequest $request)
    {
        $data = $request->validated();
        $user = auth()->user();
        $this->userService->update($user, $data);
        return response_success();
    }
}
